import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import styles from '../deliverManage/index.less';
import moment from 'moment';
import {
    Card,
    DatePicker,
    Input,
    Select,
    Checkbox,
    Form,
    Button,
    message,
    Spin,
    Modal,
    List,
    Row,
    Col,
    Icon,
    Table ,
    Avatar,
    Popover,
    Menu,
    Tooltip,
    Tag
  } from 'antd';
import HeaderTab from '@/components/HeaderTab';
import ChangeRemark from '../orderList/changeRemark';
import ExportOrder from './exportOrder';
import ReportForm from '../orderList/reportForm';
import {abs} from '@/utils/utils';


const confirm = Modal.confirm;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option,OptGroup  } = Select;

@Form.create()
class Index extends Component {
  state = {
    indeterminate:false,
    expandForm: false,
    modalVisible:false,
    batchModalVisible:false,
    expressBillModalVisible:false,
    printListModalVisible:false,
    exportLoading: false,
    searchLoading:false,
    defaultPrinter:'',
    printList:[],
    printExpressBillList:[],
    list:[],
    orderItem:[],
    formValues:{},
    checkedList:[],
    formData: {},
    paginationProps: {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 10,
      total: 0,
      current: 1,
    },
    tabs: [
        {
            title: '自提管理',
            key: `/${window.storeId}/order/pickedUp/${'0'}`,
        },
        {
            title: '自提核销',
            key: `/${window.storeId}/order/pickUpVerification`,
        },
    ],
    loadFinished:true
  }

  componentDidMount(){
    window.Isoption = true;
    const {match} =this.props;
    if(match&&match.params&&match.params.id){
      this.props.form.setFieldsValue({
        OrderNo:match.params.id!=0?match.params.id:''
      })
      this.requestList({OrderNo:match.params.id});
    }else{
      this.requestList();
    }
  }

  componentWillMount() {
    window.Isoption = false;
  }


  requestList = (params) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'orderPickUp/GetOrderList',
      payload: {
        PageIndex: params && params.current ? params.current : 1,
        PageSize: params && params.pageSize ? params.pageSize : 10,
        MinDate: params && params.MinDate ? params.MinDate : null,
        MaxDate: params && params.MaxDate ? params.MaxDate : null,
        PaymentChannel: params && params.PaymentChannel ? params.PaymentChannel : 0, //支付方式
        MemberName: params && params.MemberName ? params.MemberName : '', // 买家信息
        OrderNo: params && params.OrderNo ? params.OrderNo!=0?params.OrderNo: '':'',
        RightsStatus: params && params.RightsStatus ? params.RightsStatus : 0, // 售后
        Receiver: params && params.Receiver ? params.Receiver : '',
        GoodsKeyWord: params && params.GoodsKeyWord ? params.GoodsKeyWord : '',
        OrderStatus: params && params.OrderStatus ? params.OrderStatus : 2, //发货状态
        Sort: params && params.Sort !=undefined ? params.Sort : 1,  //降序
      },
      callBack:{
        success:(data)=>{
          const {paginationProps}=this.state;
          paginationProps.current=params &&params.current?params.current:1;
          paginationProps.pageSize=params &&params.pageSize?params.pageSize:10;
          paginationProps.total=data.Data.Total;
          this.setState({
            list:data.Data.DataList||[],
            loadFinished:false,
            searchLoading:false,
            paginationProps,
            checkedList:[], // 选择项
            indeterminate: false,
            checkAll:false
          })
        }
      }
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  clickexportOrder =() => {
    const { dispatch, form} = this.props;
    form.validateFields((err, values) => {
        if(values.Date) {
            const datas = {
                ...values,
                MaxDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
                MinDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
            };
            this.setState({
                formData: datas,
                exportLoading: true,
            })
            dispatch({
                type: 'orderList/GetTaskName',
                payload: {
                    TaskType: 0
                },
                callBack: {
                    success: res => {
                        if(res.Code===0) {
                            this.setState({
                                data: res.Data,
                                visible: true,
                                exportLoading: false,
                            })
                        }
                    },
                    error: res=> {
                        message.error(res.Msg)
                    }
                }
            })
        }
        else {
            message.error('请选择起始时间')
        }
    })
  }

  // 点击查看
clickReportForm =() => {
    const title="已生成报表";
    const TaskType = 0; //类型
    const width = 640;
    this.reportForm.show({width, title, TaskType})
}

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      cardList,
      allTagList,
      loading,
    } = this.props;
    const {exportLoading,searchLoading} = this.state;
    return (
      <Form  layout="inline">
        <Row >
          <Col span={8}>
            <FormItem label="下单时间">
              {getFieldDecorator('Date')(<RangePicker style={{ width: '100%' }} placeholder={['开始日期', '    结束日期']} />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="支付方式">
              {getFieldDecorator('PaymentChannel',{
                initialValue:0
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={0}>全部</Option>
                  <Option value={1}>微信支付</Option>
                  <Option value={2}>货到付款</Option>
                  <Option value={3}>线下支付</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="买家信息">
              {getFieldDecorator('MemberName')(
                <Input className="xkd-width-per-100" placeholder="昵称/手机号"/>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row >
          <Col span={8}>
            <FormItem label="订单号">
              {getFieldDecorator('OrderNo')(<Input style={{ width: '100%' }} placeholder="订单号"/>)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label={
                <span>
                    <span style={{marginRight: 8}}>维权状态</span>
                    <Popover
                        content={
                            <div>
                                <p>说明:</p>
                                <p>退款中商品直接发货，表示已跟买家协商好取消退款，</p>
                                <p>随订单一起发货，发货时系统会自动取消退款中状态。</p>
                            </div>
                        }
                        trigger="hover"
                        placement="top"
                    >
                        <Icon type="question-circle" style={{color: '#8c8c8c'}}/>
                    </Popover>                   
                </span>
            }>
              {getFieldDecorator('RightsStatus',{
                initialValue:0
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={0}>全部</Option>
                  <Option value={1}>退款处理中</Option>
                  <Option value={2}>退款结束</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="收货人">
              {getFieldDecorator('Receiver')(
                <Input style={{ width: '100%' }} placeholder="姓名/电话"/>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row >
          <Col span={8}>
            <FormItem label="商品信息">
              {getFieldDecorator('GoodsKeyWord')(<Input style={{ width: '100%' }} placeholder="商品名称/商品编码"/>)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="自提状态">
              {getFieldDecorator('OrderStatus',{
                initialValue:2
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={2}>备货中</Option>
                  <Option value={3}>待自提</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div className="screenNavButton">
            <Button type="primary" onClick={this.handleSearch} loading={searchLoading}>
              筛选
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            {/* <Button style={{ marginLeft: 8 }} onClick={this.clickexportOrder} loading={exportLoading}>
              批量导出
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.clickReportForm}>
              查看已生成报表
            </Button> */}
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    return this.renderAdvancedForm()
  }

  onCheckboxChange = (e,id) => {
    const {checkedList,list} = this.state;
    let checked=e.target.checked;
    //console.log(e,id)
    if(list.length){
      let index=list.findIndex(item=>item.Id==id);
      if(!checked&&index>-1){
        list[index].checked=false;
      }else if(checked&&index>-1){
        list[index].checked=true;
      }
      let index2 = checkedList.findIndex(item=>item==id);
      checked?checkedList.push(id):index2>-1?checkedList.splice(index2,1):'';
      this.setState({
        list,
        checkedList,
        indeterminate: !!checkedList.length && (checkedList.length < list.length),
        checkAll: checkedList.length === list.length,
      });
    }
  }

  onCheckAllChange = (e) => {
    const {checkedList,list} = this.state;
    let arr=[];
    let checked=e.target.checked;
    checked?list.forEach(item=>{
      item.checked=true;
      arr.push(item.Id)
    }):list.forEach(item=>{
      item.checked=false;
      arr=[];
    })
    this.setState({
      checkedList: arr,
      indeterminate: false,
      checkAll: checked,
    });
  }

  handleSearch = () => {
    const {form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        MinDate:
          fieldsValue.Date && fieldsValue.Date[0]
            ? moment(fieldsValue.Date[0]).format('YYYY-MM-DD')
            : '',
        MaxDate:
          fieldsValue.Date && fieldsValue.Date[1]
            ? moment(fieldsValue.Date[1]).format('YYYY-MM-DD')
            : '',
      };
      this.setState({
        formValues: values,
        searchLoading:true
      });
       this.requestList({ ...values });
    });
  }

  //全部备货
  clickfinishedAll =() => {
        const {checkedList} = this.state;
        const { dispatch} = this.props;
        const that = this;
        if(checkedList.length> 0) {
            Modal.confirm({
                title: '确认已完成备货?',
                okText: '确认',
                cancelText: '取消',
                onOk() {
                    dispatch({
                        type: 'orderPickUp/StockUpBatch',
                        payload: {
                            OrderIdList: checkedList
                        },
                        callBack: {
                            success: res => {
                                if(res.Code ===0) {
                                    message.success('备货成功');
                                    that.requestList()
                                }
                            },
                            error: res => {
                                message.error(res.Msg)
                            }
                        }
                    })
                }
           });
        }else {
            message.error('请选择最少一个订单');
        }
  }

    //确认备货单个
    clickfinished=(id) =>{
        const { dispatch} = this.props;
        const that = this;
        Modal.confirm({
            title: '确认已完成备货?',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                dispatch({
                    type: 'orderPickUp/StockUpBatch',
                    payload: {
                        OrderIdList: [id]
                    },
                    callBack: {
                        success: res => {
                            if(res.Code ===0) {
                                message.success('备货成功');
                                that.requestList()
                            }
                        },
                        error: res => {
                            message.error(res.Msg)
                        }
                    }
                })
            }
       });
      }


   // 头部状态切换
   onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
      }
    );
  };

  onChange = (page) => {
    this.requestList({current:page})
  }

  onShowSizeChange= (page,pageSize) => {
    this.requestList({pageSize:pageSize,current:1})
  }

  //表头筛选
  onTableChange = (pagination, filters, sorter) => {
    const {formData} = this.state;
    if(sorter.order ==='descend') {
        formData.Sort ='Desc';
    } else {
        formData.Sort ='Asc';
    }
    this.setState({
        formData,
    })
    this.requestList({Sort:sorter.order==="ascend"?0:1})
  }

   // 刷新页面
   clickrefrech = () => {
    const {formValues} = this.state;
      this.requestList();
}

lookDetail = (OrderNo) => {
  window.open(`/#/${window.storeId}/order/details/${OrderNo}`);
}


  render() {
    const columns = [
        {
          title: '商品信息',
          dataIndex: 'NickName',
          width:'20.8%'
        },
        {
          title: '单价/数量',
          dataIndex: 'Telephone',
          align: 'right',
          width: '12.5%',
        },
        {
          title: '售后',
          dataIndex: 'LastBuyTime',
          width: '8.3%',
        },
        {
          title: '收货人',
          dataIndex: 'TotalFee',
          width: '12.5%',
         // sorter: true,
        },
        {
          title: '买家信息',
          dataIndex: 'TotalFeeNum',
          width: '12%',
        },
        {
          title: '下单时间',
          dataIndex: 'SingleFee',
          width: '12%',
          sorter: true,
        },
        {
          title: '实付金额',
          dataIndex: 'TotalPoints',
          width: '12.5%',
          align: 'right',
        },
        {
          title: '操作',
         // width: '10%',
          align: 'right',
        },
      ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 2 },
        sm: { span: 2 },
        md: { span: 2 },

      },
      wrapperCol: {
        xs: { span: 22 },
        sm: { span: 22 },
        md: { span: 22 },
      },
    };
    const {
      getFieldDecorator, getFieldsError, getFieldError, isFieldTouched, getFieldValue
    } = this.props.form;
    const { list, paginationProps,indeterminate,checkAll,tabs,loadFinished,checkedList, formData,} = this.state;
    const { loading1,cdnUrl,form,} = this.props;

    const listItem= (item,index) =>{
      const iamgeVel  = item.OrderTag ===0 ?6: item.OrderTag;
      let orderIndex=list.findIndex(val=>val.Id==item.Id);

     return (
      <List.Item className={styles.listBody}>
          <Row className={styles.navtebalRow}>
              <Col span={18} className={styles.orderNo}>
                  <Checkbox onChange={(e)=>this.onCheckboxChange(e,item.Id)} checked={item.checked}>订单号：{item.OrderNo}</Checkbox>
                  <span className="xkd-ml16">{item.DeliveryTypeName +' / '+item.PaymentChannelNameStr}</span>
              </Col>
              <Col span={6}>
                  <div style={{textAlign: 'right', paddingRight: 16}}>
                      {
                        item.Remark?
                        <Popover title="买家留言" content={item.Remark?item.Remark:'无'}>
                            <span>
                                <img
                                    src={cdnUrl + '/' + 'xkdnewyun/systemfile/store/icon/orderlist-wx.png' +'?x-oss-process=style/240'}
                                    width={16}
                                    height={16}
                                />
                            </span>
                        </Popover>:null
                      }
                      <span className="xkd-ml16" onClick={
                          () => {
                              const title="修改备注";
                              const OrderNo = item.OrderNo;
                              this.changeRemark.show({title, OrderNo}, this.clickrefrech)
                          }
                      }>
                        {item.MerchantRemark?(<Tooltip title={item.MerchantRemark}>
                             <img
                                src={cdnUrl + '/' + `xkdnewyun/systemfile/store/icon/orderlist-remark0${iamgeVel}.png` +'?x-oss-process=style/240'}
                                width={16}
                                height={16}
                             />
                            </Tooltip>):(
                                 <img
                                 src={cdnUrl + '/' + `xkdnewyun/systemfile/store/icon/orderlist-remark0${iamgeVel}.png` +'?x-oss-process=style/240'}
                                 width={16}
                                 height={16}
                              />
                        )}
                      </span>
                  </div>
              </Col>
          </Row>
          <Row className={styles.navRowItem} style={{height: `${item.OrderItem.length * 96}px`}}>
              <Col span={10}>
                  <List
                      dataSource={item.OrderItem ?item.OrderItem:[]}
                      renderItem={(data, index) => {
                          return (
                              <Row className={item.OrderItem.length === index+ 1 ?styles.leftItemNoborder : styles.leftItem}>
                                  <Col span={19}>
                                      <List.Item key={data.Id} className={styles.listItem}>
                                          <List.Item.Meta
                                              avatar={<Avatar src={cdnUrl + '/' + data.ThumbnailUrl +'?x-oss-process=style/240'} />}
                                              title={
                                                  <span title={data.ProductName} style={{maxWidth:145,height:40}}>
                                                      {data.ProductName}
                                                  </span>
                                              }
                                              description={
                                                  <span
                                                      title={data.SkuName}
                                                      className="xkd-text-ellipsis"
                                                  >{data.SkuName}</span>
                                              }
                                          />
                                            <div>
                                                  <div>{'￥' +abs(data.SingleFee,2)}</div>
                                                  <div>{'x'+ data.BuyNum}</div>
                                              </div>
                                      </List.Item>
                                  </Col>
                                  <Col span={5}>{data.RightsStatusName}</Col>
                              </Row>
                          )
                      }}
                  >
                  </List>
              </Col>
              <Col span={3}>
                <div >
                    <div>{item.ReceivingName}</div>
                    <div>{item.ReceivingTelephone}</div>
                </div>
              </Col>
              <Col span={3}>
                <div >
                    <div>{item.MemberName}</div>
                    <div>{item.MemberTelephone}</div>
                </div>
              </Col>
              <Col span={3} >
                  <span>{item.CreateTime}</span>
              </Col>
              <Col span={3}>
                <div className="xkd-text-right" >
                    <div className={styles.price}>￥{abs(item.OrderPayAmount,2)}</div>
                    {/* <div className={`${styles.freightColor} xkd-font12`}>(含运费￥{abs(item.OrderPayFreightAmount,2)})</div> */}
                    {!item.HasPayed&&<div className={`xkd-font12`} style={{color: 'red'}}>未付款</div>}
                </div>
              </Col>
              <Col span={2} style={{textAlign: 'right'}}>
                <div className="xkd-text-right" index={orderIndex}>
                    {item.OrderStatus===2&&(
                        <Button type="primary" size="small" onClick={()=>this.clickfinished(item.Id)} style={{width:72}}>完成备货</Button>
                    )}
                    <Button size="small" style={{marginTop:8,}} onClick={()=>this.lookDetail(item.OrderNo)}>查看详情</Button>
                </div>
              </Col>
          </Row>
      </List.Item>
     );
    }
    return (
      <Fragment>
        {/* <HeaderTab
          _this={this}
          type="slider"
          activeId={this.state.activeId}
          onChange={this.onTabChange}
          tabs={tabs}
        >
        </HeaderTab> */}
        <Spin spinning={loadFinished}>
        <Card
        bordered={false}
            className={styles.deliverManage}
        >
            <div style={{background:'#fafafa',marginBottom:16,paddingTop:16,paddingRight:16,boxSizing:'border-box'}}>
                <div className="tableListForm">{this.renderForm()}</div>
            </div>
            <div style={{paddingLeft:16}}>
                <Checkbox
                  indeterminate={indeterminate}
                  onChange={this.onCheckAllChange}
                  checked={checkAll}
                >
                  当页全选
                </Checkbox>
                <Button style={{ marginLeft: 8 }} onClick={this.clickfinishedAll}>
                    批量备货
                </Button>
            </div>
            <List
                header={
                    <div>
                         <Table
                            //loading={loading}
                            //rowKey={record => record.Id}
                            dataSource={null}
                            columns={columns}
                            // rowSelection={rowSelection}
                            onChange={this.onTableChange}
                           // pagination={paginationProps}
                        />
                    </div>
                }
               // bordered={true}
               itemLayout="vertical"
                dataSource={list}
                pagination={{...paginationProps,onChange:this.onChange,onShowSizeChange:this.onShowSizeChange}}
                renderItem={item => listItem(item)}
                loading={loading1}
            />
        </Card>
        <ChangeRemark //备注
            ref ={e => {
                this.changeRemark = e;
            }}
        />
        <ExportOrder _this = {this} visible={this.state.visible} data={formData} />
        <ReportForm
                ref={e => {
                    this.reportForm = e;
                }}
            />
        </Spin>
      </Fragment>
    )
  }
}
export default connect(({ deliverManage, global, loading }) => ({
  cdnUrl:global.oemInfo.cdnUrl,
  oemInfo:global.oemInfo,
  loading1: loading.effects['orderPickUp/GetOrderList'],
  allLoading:loading.global,
}))(Index);
